/*
 * @Descripttion:
 * @version:
 * @Author: sueRimn
 * @Date: 2020-10-20 17:48:29
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-11-13 10:09:06
 */
import { removeToken, setSessionInfo } from '@/utils/auth'
import { get_Login } from '@/api/user'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
    return {
        name: '',
        avatar: '',
        institute_id: '', // 机构id
        k_token: null, // abe2024445d8dfcc5a52904faea6a5b1
        sideBarRoles: [],
        pageRoles: [],
        userId: ''
    }
}

const state = getDefaultState()

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_K_TOKEN: (state, k_token) => {
        state.k_token = k_token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    },
    SET_INSTITUTE: (state, institute_id) => {
        state.institute_id = institute_id
    },
    SET_SIDEBAROLES: (state, sideBarRoles) => {
        state.sideBarRoles = sideBarRoles
    },
    SET_PAGROLES: (state, pageRoles) => {
        state.pageRoles = pageRoles
    },
    SET_USERID: (state, userId) => {
        state.userId = userId
    }

}

const actions = {
    // user login
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            get_Login({ username: username.trim(), password: password }).then(response => {
                if (response.code == 200) {
                    var { data } = response
                    commit('SET_K_TOKEN', data.k_token)
                    commit('SET_NAME', data.nickname)
                    commit('SET_AVATAR', data.avatar || require('@/assets/logo/logo.png'))
                    commit('SET_INSTITUTE', data.parent_id)
                    commit('SET_SIDEBAROLES', data.menu_auth)
                    var rolesArr = data.auth.map(el => {
                        if (el.auth_id) {
                            return el.auth_id
                        } else {
                            return el
                        }
                    })
                    commit('SET_PAGROLES', rolesArr)
                    commit('SET_USERID', data.user_id)
                    setSessionInfo(JSON.stringify(userInfo))
                }
                console.log('登录', response)
                resolve(response)
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken() // must remove  token  first
            commit('RESET_STATE')
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

